<template>
  <div class="tcp-connect">
    <div class="tcp-connect__mask"></div>
    <Dialog v-model="showModal" theme="round-button" show-cancel-button title="TCP服务" confirm-button-text="连接"
      :beforeClose="beforeClose">
      <Input placeholder="请输入服务器地址" v-model="server" class="tcp-connect__input" />
      <Input placeholder="请输入端口" v-model="port" class="tcp-connect__input" />
      <div class="tcp-connect__error" @click="connect">{{ error }}</div>
    </Dialog>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Emit } from 'vue-property-decorator';
import Dialog from '@/components/dialog';
import Input from '@/components/input';
import { isDevelopment, log } from '@/utils'
import MySocket from '@/modules/socket';
import { storage } from '@/modules/storage';

@Component({
  name: 'BlueTooth',
  components: {
    Dialog,
    Input,
  },
})
export default class TCPConnect extends Vue {
  // 显示蓝牙列表
  private showModal = true;
  // 服务器地址
  private server = '';
  // 端口
  private port = '';
  // socket
  private socket: typeof window.Socket | null = null;
  // 错误信息
  private error = '';

  mounted() {
    this.server = storage.get('tcp-server') || '';
    this.port = storage.get('tcp-port') || '';

    if (window.Socket) {
      this.socket = MySocket.getInstance();
      console.log(this.socket);
      // 错误处理
      this.socket.onError = function (error: string) {
        console.error("TCP服务发生错误: " + error);
      };
      this.socket.onClose = function () {
        console.log("TCP连接断开");
      };
    }
  }

  beforeClose(action: 'confirm' | 'cancel', done: (cb?: boolean) => void) {
    if (action === 'confirm') {
      this.connect();
      done(false)
    }
    if (action === 'cancel') {
      this.$router.back();
    }
  }

  private connect() {
    log('连接TCP服务', this.server, this.port);
    storage.set('tcp-server', this.server);
    storage.set('tcp-port', this.port);
    if (isDevelopment()) {
      this.handleConfirm();
      return;
    }
    if (!this.socket) {
      return;
    }
    if (!this.server) {
      this.error = '请输入服务器地址';
      return;
    }
    if (!this.port) {
      this.error = '请输入端口号';
      return;
    }
    this.socket.open(this.server, Number(this.port), () => {
      log('TCP服务连接成功');
      this.showModal = false;
      this.handleConfirm();
    }, (err: string) => {
      log('TCP服务连接失败', err);
    });
  }

  @Emit('confirm')
  handleConfirm() {
    this.showModal = false;
  }

}
</script>

<style lang="scss" scoped>
.tcp-connect {
  background-color: rgba(255, 255, 255, 1);
  width: 100vw;
  height: 100vh;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 10;
  margin-top: 80px;

  &__mask {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.4);
  }

  &__input {
    margin: 4px 0;
    width: 100%;
  }

  &__error {
    width: 100%;
    text-align: left;
    color: #ff4d4f;
  }

}
</style>
